const OPERATORS = {
    'INT': ['exact', 'in', 'gt', 'gte', 'lt', 'lte', 'range', 'isnull'],
    'BOOL': ['exact', 'in', 'isnull'],
    'DATE': ['exact', 'in', 'gt', 'gte', 'lt', 'lte', 'range', 'isnull'],
    'STR': ['exact', 'iexact', 'contains', 'icontains', 'in', 'gt', 'gte', 'lt', 'lte', 'range',
        'startswith', 'endswith', 'regex', 'iregex', 'istartswith', 'iendswith', 'isnull'],
    'FLOAT': ['exact', 'in', 'gt', 'gte', 'lt', 'lte', 'range', 'isnull']
};

// 运算符显示文本
const OPERATOR_TEXTS = {
    'exact': '等于',
    'iexact': '等于(忽略大小写)',
    'contains': '包含',
    'icontains': '包含(忽略大小写)',
    'in': '在列表中',
    'gt': '大于',
    'gte': '大于等于',
    'lt': '小于',
    'lte': '小于等于',
    'range': '范围',
    'startswith': '开头为',
    'endswith': '结尾为',
    'istartswith': '开头为(忽略大小写)',
    'iendswith': '结尾为(忽略大小写)',
    'regex': '正则匹配',
    'iregex': '正则匹配(忽略大小写)',
    'isnull': '为空'
};

// 页面初始化
document.addEventListener('DOMContentLoaded', function () {
    // 加载标签并添加第一个条件
    loadTags().then(() => {
        addCondition();
    }).catch(error => {
        console.error('初始化失败:', error);
        alert('无法加载标签数据，请刷新页面重试');
    });

    // 添加条件按钮
    document.getElementById('add-condition').addEventListener('click', addCondition);

    // 生成JSON按钮
    document.getElementById('generate-json').addEventListener('click', generateJSON);

    // 重置表单
    document.getElementById('reset-form').addEventListener('click', resetForm);

    // 复制JSON按钮
    document.getElementById('copy-json').addEventListener('click', copyJSONToClipboard);
});

let conditionId = 0;

// 添加新条件
function addCondition() {
    const template = document.getElementById('condition-template');
    const clone = template.cloneNode(true);
    clone.style.display = '';
    clone.id = '';

    // 为每个条件生成唯一ID
    const id = ++conditionId;
    clone.innerHTML = clone.innerHTML.replace(/{id}/g, id);

    document.getElementById('query-conditions').appendChild(clone);
    initCondition(clone);
}

// 初始化条件控件
function initCondition(conditionElement) {
    const fieldSelect = conditionElement.querySelector('.field-select');
    const operatorSelect = conditionElement.querySelector('.operator-select');
    const valueContainer = conditionElement.querySelector('.value-container');
    const removeBtn = conditionElement.querySelector('.remove-condition');

    // 字段选择变化时更新运算符和值输入
    fieldSelect.addEventListener('change', function () {
        updateOperators(this, operatorSelect);
        updateValueInput(this, operatorSelect, valueContainer);
    });

    // 运算符变化时更新值输入
    operatorSelect.addEventListener('change', function () {
        updateValueInput(fieldSelect, this, valueContainer);
    });

    // 移除条件
    removeBtn.addEventListener('click', function () {
        conditionElement.remove();
    });

    // 初始化运算符
    updateOperators(fieldSelect, operatorSelect);
    updateValueInput(fieldSelect, operatorSelect, valueContainer);
}

// 更新运算符下拉框
function updateOperators(fieldSelect, operatorSelect) {
    const fieldType = fieldSelect.selectedOptions[0].dataset.type;
    const currentOp = operatorSelect.value;

    operatorSelect.innerHTML = '';

    OPERATORS[fieldType].forEach(op => {
        const option = document.createElement('option');
        option.value = op;
        option.textContent = OPERATOR_TEXTS[op] || op;
        operatorSelect.appendChild(option);
    });

    // 保持当前选中的运算符（如果可用）
    if (currentOp && OPERATORS[fieldType].includes(currentOp)) {
        operatorSelect.value = currentOp;
    }
}

// 更新值输入控件
function updateValueInput(fieldSelect, operatorSelect, valueContainer) {
    const fieldType = fieldSelect.selectedOptions[0].dataset.type;
    const operator = operatorSelect.value;

    valueContainer.innerHTML = '';

    if (operator === 'isnull') {
        // 布尔选择 (是否为空)
        const select = document.createElement('select');
        select.className = 'form-control';
        select.name = 'value';
        select.required = true;

        ['true', 'false'].forEach(val => {
            const option = document.createElement('option');
            option.value = val;
            option.textContent = val === 'true' ? '是' : '否';
            select.appendChild(option);
        });

        valueContainer.appendChild(select);
    }
    else if (operator === 'in') {
        // 多值输入
        const div = document.createElement('div');
        div.className = 'multi-value-input';
        div.innerHTML = `
            <textarea class="form-control" name="value" placeholder="每行一个值" required></textarea>
            <small class="form-text text-muted">每行输入一个值</small>
        `;
        valueContainer.appendChild(div);
    }
    else if (operator === 'range') {
        // 范围输入
        const div = document.createElement('div');
        div.className = 'range-input';
        div.innerHTML = `
            <div class="row g-2">
                <div class="col">
                    <input type="${getInputType(fieldType)}" class="form-control" name="min" placeholder="最小值" required>
                </div>
                <div class="col">
                    <input type="${getInputType(fieldType)}" class="form-control" name="max" placeholder="最大值" required>
                </div>
            </div>
        `;
        valueContainer.appendChild(div);
    }
    else {
        // 单值输入
        if (fieldType === 'BOOL') {
            // 布尔值使用下拉框
            const select = document.createElement('select');
            select.className = 'form-control';
            select.name = 'value';
            select.required = true;

            ['true', 'false'].forEach(val => {
                const option = document.createElement('option');
                option.value = val;
                option.textContent = val === 'true' ? '是' : '否';
                select.appendChild(option);
            });

            valueContainer.appendChild(select);
        } else {
            const input = document.createElement('input');
            input.type = getInputType(fieldType);
            input.className = 'form-control';
            input.name = 'value';
            input.placeholder = '输入值';
            input.required = true;

            // 为日期类型添加最小/最大限制
            if (fieldType === 'DATE') {
                input.min = '2000-01-01';
                input.max = new Date().toISOString().split('T')[0];
            }

            valueContainer.appendChild(input);
        }
    }
}

// 根据字段类型获取输入类型
function getInputType(fieldType) {
    switch (fieldType) {
        case 'INT': return 'number';
        case 'FLOAT': return 'number';
        case 'DATE': return 'date';
        default: return 'text';
    }
}

// 从API加载标签
async function loadTags() {
    try {
        const response = await fetch('/api/gettags/');
        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
        const tags = await response.json();

        const tagsOptgroup = document.getElementById('tags-optgroup');
        tagsOptgroup.innerHTML = '';

        tags.forEach(tag => {
            const option = document.createElement('option');
            option.value = tag.name;
            option.textContent = `${tag.name} (${getTypeDisplay(tag.tag_type)})`;
            option.dataset.type = tag.tag_type;
            option.dataset.isbasic = "false";
            tagsOptgroup.appendChild(option);
        });
    } catch (error) {
        console.error('加载标签失败:', error);
        throw error;
    }
}

// 辅助函数：获取类型显示文本
function getTypeDisplay(tagType) {
    const typeMap = {
        'BOOL': '布尔值',
        'INT': '整数',
        'STR': '字符串',
        'FLOAT': '浮点数',
        'DATE': '日期'
    };
    return typeMap[tagType] || tagType;
}

// 生成JSON
function generateJSON() {
    const conditions = [];
    const conditionElements = document.querySelectorAll('#query-conditions .condition-card');

    // 验证至少有一个条件
    if (conditionElements.length === 0) {
        alert('请至少添加一个搜索条件');
        return;
    }

    // 构建条件数组
    for (const cond of conditionElements) {
        try {
            const condition = buildConditionObject(cond);
            conditions.push(condition);
        } catch (error) {
            alert(`条件配置错误: ${error.message}`);
            return;
        }
    }

    // 最后一个条件不需要逻辑关系
    if (conditions.length > 0) {
        delete conditions[conditions.length - 1].logic;
    }

    // 显示生成的JSON
    const jsonOutput = document.getElementById('json-output');
    const jsonString = JSON.stringify({ query: conditions }, null, 2);
    jsonOutput.textContent = "172.16.10.20/api/random?query=" + jsonString;

    // 启用复制按钮
    document.getElementById('copy-json').disabled = false;

    // 滚动到JSON输出区域
    jsonOutput.scrollIntoView({ behavior: 'smooth' });
}

// 构建单个条件对象
function buildConditionObject(condElement) {
    const fieldSelect = condElement.querySelector('.field-select');
    const operatorSelect = condElement.querySelector('.operator-select');
    const logicSelect = condElement.querySelector('.logic-select');
    const notCheckbox = condElement.querySelector('.not-checkbox');
    const operator = operatorSelect.value;

    const condition = {
        tag: fieldSelect.value,
        type: fieldSelect.selectedOptions[0].dataset.type,
        oper: operator,
        is_basic: fieldSelect.selectedOptions[0].dataset.isbasic === 'true',
        logic: logicSelect.value,
        not: notCheckbox.checked
    };

    // 处理不同的值输入方式
    if (operator === 'in') {
        const values = condElement.querySelector('textarea').value
            .split('\n')
            .map(v => v.trim())
            .filter(v => v !== '');

        if (values.length === 0) throw new Error('请输入至少一个值');
        condition.value = { value: values };
    }
    else if (operator === 'range') {
        const min = condElement.querySelector('input[name="min"]').value;
        const max = condElement.querySelector('input[name="max"]').value;

        if (!min || !max) throw new Error('请输入范围值');
        condition.value = { min, max };
    }
    else if (operator === 'isnull') {
        condition.value = { value: condElement.querySelector('select[name="value"]').value };
    }
    else {
        const value = condElement.querySelector('input[name="value"], select[name="value"]').value;
        if (!value && value !== false) throw new Error('请输入值');
        condition.value = { value };
    }

    return condition;
}

// 复制JSON到剪贴板
function copyJSONToClipboard() {
    const jsonOutput = document.getElementById('json-output');
    const jsonText = jsonOutput.textContent;

    navigator.clipboard.writeText(jsonText).then(() => {
        // 显示成功消息
        const copyBtn = document.getElementById('copy-json');
        const originalHtml = copyBtn.innerHTML;

        copyBtn.innerHTML = '<i class="bi bi-check"></i> 已复制';
        copyBtn.classList.remove('btn-outline-primary');
        copyBtn.classList.add('btn-success');

        // 2秒后恢复原状
        setTimeout(() => {
            copyBtn.innerHTML = originalHtml;
            copyBtn.classList.remove('btn-success');
            copyBtn.classList.add('btn-outline-primary');
        }, 2000);
    }).catch(err => {
        console.error('复制失败:', err);
        alert('复制失败，请手动选择并复制文本');
    });
}

// 重置表单
function resetForm() {
    if (confirm('确定要重置所有条件吗？')) {
        document.getElementById('query-conditions').innerHTML = '';
        document.getElementById('json-output').textContent = '// 生成的JSON将显示在这里';
        document.getElementById('copy-json').disabled = true;
        conditionId = 0;
        addCondition(); // 添加一个空条件
    }
}